package com.linln.common.utils;

import org.apache.logging.log4j.util.Strings;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ObjectUtil {
    public static Map<String, Object> ObjectToMap(Object obj) throws IllegalAccessException, JSONException, InvocationTargetException {
        Class objClass = obj.getClass();
        Field[] fs = objClass.getDeclaredFields();
        Map<String, Object> data = new HashMap<>();
        for (Field field : fs) {
            String fieldName = field.getName();
            field.setAccessible(true);
            if (fieldName.equals("props")) {
                JSONObject jsonObject = new JSONObject(Strings.isBlank((String)field.get(obj))?"{}":(String)field.get(obj));
                Map<String, Object> map = new HashMap<String, Object>();
                Iterator it = jsonObject.keys();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    Object value = jsonObject.get(key);
                    map.put(key, value);
                }
                data.putAll(map);
            } else {
                Object value = field.get(obj);
                data.put(fieldName, value);
            }
        }
        return data;
    }
}
